package com.benjaminwan.read.free.ui.script

import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.afollestad.assent.Permission
import com.afollestad.assent.runWithPermissions
import com.airbnb.mvrx.activityViewModel
import com.airbnb.mvrx.withState
import com.benjaminwan.read.free.R
import com.benjaminwan.read.free.base.adapter.simpleController
import com.benjaminwan.read.free.base.fragment.BaseFragment
import com.benjaminwan.read.free.databinding.FragmentScriptBinding
import com.benjaminwan.read.free.model.action.Position
import com.benjaminwan.read.free.model.action.Script
import com.benjaminwan.read.free.ui.main.MainViewModel
import com.benjaminwan.read.free.utils.actionRightMenu
import com.benjaminwan.read.free.utils.copySwap
import com.benjaminwan.read.free.utils.groupRightMenu
import com.benjaminwan.read.free.utils.loadFromFile
import com.benjaminwan.read.free.utils.saveFile
import com.benjaminwan.read.free.utils.setMarginItemDecoration
import com.benjaminwan.read.free.utils.shareSaveFile
import com.benjaminwan.read.free.views.actionItemView

class ScriptFragment : BaseFragment(), View.OnClickListener {

    private val mainVM by activityViewModel(MainViewModel::class)
    private val epoxyController by lazy { epoxyController() }

    private lateinit var binding: FragmentScriptBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentScriptBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        epoxyController.onRestoreInstanceState(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        epoxyController.onSaveInstanceState(outState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setHasOptionsMenu(true)
        initViews()
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        menu.clear()
        inflater.inflate(R.menu.menu_script, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean =
        when (item.itemId) {
            R.id.menu_open_script -> {
                runWithPermissions(Permission.READ_EXTERNAL_STORAGE) {
                    loadFromFile(mainVM)
                }
                true
            }

            R.id.menu_save_script -> {
                saveFile(mainVM)
                true
            }

            R.id.menu_share -> {
                shareSaveFile(mainVM)
                true
            }

            R.id.menu_clear_script -> {
                mainVM.setScript(Script())
                true
            }

            R.id.menu_copy_clipboard -> {
                mainVM.toClipBoard()
                true
            }

            R.id.menu_paste_replace -> {
                mainVM.fromClipBoardReplace()
                true
            }

            R.id.menu_paste_add -> {
                mainVM.fromClipBoardAdd()
                true
            }

            R.id.menu_add_group -> {
                mainVM.addGroup()
                true
            }

            else -> {
                super.onOptionsItemSelected(item)
            }
        }

    /*override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        onSAFResult(requestCode, resultCode, data, mainVM)
    }*/

    private fun initViews() {
        binding.actionScriptRv.setHasFixedSize(true)
        binding.actionScriptRv.setMarginItemDecoration(2, 1, 2, 1)
        binding.actionScriptRv.setController(epoxyController)
        //binding.testBtn.setOnClickListener(this)
    }

    override fun onClick(view: View?) {
        view ?: return
        when (view.id) {
            /*R.id.testBtn -> {
                val action1 = listOf<Action>(
                    KeyboardClick(0x85),
                    Delay((2000L..3000L)),
                    KeyboardClick(0x86),
                    Delay((2000L..3000L))
                )
                *//*val action99: MutableList<Action> = mutableListOf()
                (1..999).forEach {
                    action99.add(KeyboardClick(0x85))
                }
                val group99 = Group(action99, memo = "组99")*//*
                val group1 =
                    Group(action1)
                val action2 = listOf<Action>(
                    MouseDragPage(
                        Horizontal.RIGHT, Vertical.UP, (80..150), (5..10), (3..8), (1..3)
                    ),
                    Delay(),
                    MouseDragPage(
                        Horizontal.LEFT, Vertical.DOWN, (80..150), (5..10), (3..8), (1..3)
                    ),
                    Delay(),
                    KeyboardClick(0x85),
                    Delay((2000L..3000L)),
                    KeyboardClick(0x86),
                    Delay((2000L..3000L))
                )
                val group2 = Group(
                    action2,
                    memo = "组2"
                )
                val action3 = listOf<Action>(
                    MouseDragPage(
                        Horizontal.RIGHT, Vertical.UP, (80..150), (5..10), (3..8), (1..3)
                    ),
                    Delay(),
                    MouseDragPage(
                        Horizontal.LEFT, Vertical.DOWN, (80..150), (5..10), (3..8), (1..3)
                    ),
                    Delay(),
                    KeyboardClick(0x85),
                    Delay(),
                    KeyboardClick(0x86)
                )
                val group3 = Group(
                    action3,
                    memo = "组3"
                )
                val action4 = listOf<Action>(
                    KeyboardClick(0x85),
                    Delay(),
                    KeyboardClick(0x86),
                    Delay()
                )
                val group4 =
                    Group(
                        action4,
                        (2..2),
                        "组4"
                    )
                val groups = listOf<Group>(
                    group1, group2, group3, group4//, group99
                )
                val script =
                    Script(groups = groups)
                mainVM.setScript(script)
            }*/
            else -> {
            }
        }
    }

    override fun invalidate() = withState(mainVM) { main ->
        requireActivity().invalidateOptionsMenu()
        binding.actionScriptRv.requestModelBuild()
    }

    private fun epoxyController() = simpleController(mainVM) { main ->
        val script = main.script
        actionItemView {
            id("ScriptEditGlobal:${script.hashCode()}")
            actionIndex("Global")
            actionType("Config(${script.memo})")
            actionParam(script.toString())
            backgroundRes(R.drawable.bg_red5_to_red7)
            onClickListener { view ->
                findNavController().navigate(
                    R.id.action_scriptFragment_to_actionFragment,
                    ActionFragment.arg(Position())
                )
            }
        }
        script.groups.forEachIndexed { idGroup, group ->
            actionItemView {
                id("ScriptEditGroup:${idGroup}${script.hashCode()}${group.hashCode()}")
                actionIndex("G${idGroup + 1}")
                actionType("Group${idGroup + 1}(${group.memo})")
                actionParam(group.toString())
                backgroundRes(R.drawable.bg_orange5_to_orange7)
                marginLeft(0)
                onClickListener { view ->
                    findNavController().navigate(
                        R.id.action_scriptFragment_to_groupFragment,
                        GroupFragment.arg(idGroup)
                    )
                }
                rightMenu(groupRightMenu.filterNot {
                    (idGroup == 0 && it.id == 1) || (idGroup == (script.groups.size - 1) && it.id == 2)
                })
                onRightMenuClickListener { swipeMenuLayout, item ->
                    when (item.id) {
                        0 -> mainVM.setGroup(idGroup, null)
                        1 -> {
                            val groups = script.groups.copySwap(idGroup, idGroup - 1)
                            mainVM.setScript(script.copy(groups = groups))
                        }

                        2 -> {
                            val groups = script.groups.copySwap(idGroup, idGroup + 1)
                            mainVM.setScript(script.copy(groups = groups))
                        }

                        3 -> {//复制组
                            val groupCopied = group.copy(memo = "复制 ${group.memo}")
                            mainVM.addGroup(idGroup + 1, groupCopied)
                        }
                    }

                    swipeMenuLayout.closeMenu()
                }
            }
            group.actions.forEachIndexed { idAction, action ->
                actionItemView {
                    id("ScriptEditAction:${idGroup}:${idAction}${script.hashCode()}${group.hashCode()}${action.hashCode()}")
                    actionIndex("A${idAction + 1}")
                    actionType(action.actionType.name)
                    actionParam(action.toString())
                    backgroundRes(R.drawable.bg_blue5_to_blue7)
                    marginLeft(1)
                    onClickListener { view ->
                        findNavController().navigate(
                            R.id.action_scriptFragment_to_actionFragment,
                            ActionFragment.arg(
                                Position(idGroup, idAction)
                            )
                        )
                    }
                    rightMenu(actionRightMenu.filterNot {
                        (idAction == 0 && it.id == 1) || (idAction == (group.actions.size - 1) && it.id == 2)
                    })
                    onRightMenuClickListener { swipeMenuLayout, item ->
                        when (item.id) {
                            0 -> mainVM.setAction(
                                Position(idGroup, idAction), null
                            )

                            1 -> {
                                val actions = group.actions.copySwap(idAction, idAction - 1)
                                mainVM.setGroup(idGroup, group.copy(actions = actions))
                            }

                            2 -> {
                                val actions = group.actions.copySwap(idAction, idAction + 1)
                                mainVM.setGroup(idGroup, group.copy(actions = actions))
                            }
                        }
                        swipeMenuLayout.closeMenu()
                    }
                }
            }
        }
    }

}